package com.efounder.activity;



import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.core.xml.StubObject;
import com.efounder.forwechat.BaseApp;
import com.efounder.fragment.FragmentFirst;
import com.efounder.fragment.MoreMenuFrag;
import com.efounder.ospmobilelib.R;
import com.efounder.service.Registry;
import com.efounder.util.AbFragmentManager;
import com.efounder.util.AbLogUtil;
import com.efounder.util.AbToastUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.view.titlebar.AbBottomBar;
import com.efounder.view.titlebar.AbTitleBar;
import com.efounder.widget.TabBarNew;
import com.efounder.widget.TabBarNew.OnCurrentTabChangedListener;
import com.pansoft.resmanager.ResFileManager;
import com.pansoft.xmlparse.FormatSet;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
//import com.pansoft.xmlparse.MenuList;
//import com.pansoft.xmlparse.MenuParse;
/**
 * 主框架界面  2014.12.01
 * @author long
 *
 */
public class MainFrameActivity extends AbActivity implements OnCurrentTabChangedListener{
	public static final String TAG = "MainFrameActivity";
	
	private FragmentManager fm;
	private AbTitleBar mTitleBar = null;
	private AbBottomBar mBottomBar = null;
	private TextView isShowTv;
	static MainFrameActivity mySelf;
	
	FormatSet formatSet ;
	/**
	 * 默认展示页
	 */
	private final static int inittab = 0;
	/**当前Tab页面索引*/ 
	private int currentTab;
	
	/**
	 * 底部按钮是否正在显示状态
	 */
	private boolean isShowing;
	
	private List<StubObject> mainMenus; // 主菜单
	private List<StubObject> defaultMenus;
	/** 获取主菜单时用到的键值， 也是XML中主菜单的标签名 ： <menuRoot> */
	public static final String KEY_MENU_ROOT = "menuRoot";
	public Fragment[] cachedFragments; // 缓存主菜单对应的Fragments
	/**
	 * 标题名称
	 */
	String titleName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setAbContentView(R.layout.titlebar_main);
		initView();
		initData();
		initListener();
		//设置默认显示的标签页
		fm = getSupportFragmentManager();
		//默认显示  标签页 避免空白页
		fm.beginTransaction().replace(R.id.content, new FragmentFirst()).commit();
	}

	private void initData() {
		BaseApp.actManager.putActivity(TAG, this);
		mySelf = this;
		isShowing = true;
	}

	/**
	 * 设置监听事件
	 */
	private void initListener() {
		//绑定返回按键
		mTitleBar.setLogoOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				BaseApp.actManager.removeActivity(TAG);
			}
		});
		
	}

	/**
	 * 初始化UI
	 */
	private void initView() {
		new AsyncTask<Void, Void, Void>(){
			@Override
			protected Void doInBackground(Void... params) {
				// 后台下载并解析菜单, 并且获取主菜单
				File file = new File(ResFileManager.UNZIP_DIR);
				AbLogUtil.i(TAG, "---2---filePath="+file.getAbsolutePath());
//				MenuParse.getMenu(file);
//				mainMenuList = MenuList.getMenuList(KEY_MENU_ROOT);
//				defaultMenus = MenuList.getMenuList("DefaultOpenMenu");
				mainMenus = Registry.getRegEntryList(KEY_MENU_ROOT);
				defaultMenus = Registry.getRegEntryList("DefaultOpenMenu");
				if(mainMenus == null&&defaultMenus!=null){
					mainMenus = defaultMenus;
				}
				return null;
			}
			
			protected void onPostExecute(Void result) {
				// 加载完主菜单之后调用, 用于显示主菜单等操作
				makeMainMenu();
			}
			
		}.execute();
		
		mTitleBar = this.getTitleBar();
		mBottomBar = this.getBottomBar();
		mTitleBar.setTitleText("ESPMobile");
		mTitleBar.setTitleTextColor(Color.BLACK);
        mTitleBar.setLogo(R.drawable.ef_title_view_back);
        mTitleBar.getLogoView().setVisibility(View.INVISIBLE);//设置该动作 保证标题居中
        mTitleBar.setTitleBarBackground(R.color.title_bar_bg);
        mTitleBar.setTitleBarGravity(Gravity.CENTER, Gravity.CENTER);
//		mTitleBar.clearRightView();
//		View rightViewMore = mInflater.inflate(R.layout.more_btn, null);
//		mTitleBar.addRightView(rightViewMore);
//		mTitleBar.setTitleTextMargin(20, 0, 0, 0);
//		isShowTv = (TextView) rightViewMore.findViewById(R.id.moreBtn);
		//主界面
//		isShowTv.setText("隐藏菜单");
//		rightViewMore.setVisibility(View.INVISIBLE);
	}

	/**
	 * 加载完主菜单之后调用, 生存主菜单布局
	 */
	private void makeMainMenu() {
		if (mainMenus == null) {
			Toast.makeText(this, ResStringUtil.getString(R.string.common_text_http_request_data_fail), Toast.LENGTH_SHORT)
					.show();
			this.finish();
			return;
		}
		AbLogUtil.i(TAG, "mainMenuList.size():"+mainMenus.size());
		if(mainMenus.size()>TabBarNew.MAX_BOTTOM_ITEMS){
			cachedFragments = new Fragment[mainMenus.size()+1];
		}else
		cachedFragments = new Fragment[mainMenus.size()];
		loadBottomBar(mainMenus);
	}
	private void loadBottomBar(List<StubObject> espMenuList) {
		mBottomBar.setVisibility(View.VISIBLE);
		TabBarNew tb = new TabBarNew(this, espMenuList);
//		TabBar tabbarView = new TabBar(this, espMenuList);
		mBottomBar.addView(tb);
		tb.setOnCurrentTabChangedListener(this);
		currentTab = inittab;
		Fragment firstFrag = initAndCacheFragment(inittab);
		showFragment(firstFrag);
	}
	
	/**
	 * 描述：返回.退出
	 */
	private boolean isExit;
	@Override
	public void onBackPressed() {
		if (!isExit) {
			AbToastUtil.showToast(MainFrameActivity.this,"再按一次退出程序");
			isExit = true;
			new Timer().schedule(new TimerTask() {
				@Override
				public void run() {
					isExit = false;
					this.cancel();
				}
			}, 2000);
		} else {
			BaseApp.actManager.closeAllActivity();
//			MenuList.clearRegistry();
			mySelf = null;
			TabBarNew.BOTTOM_ITEM = 4;//回复底部菜单默认项 避免菜单重新加载时底部菜单个数不匹配问题
			super.onBackPressed();
		}
	}

	@Override
	public void onCurrentTabChanged(int index) {
		// 缓存并显示fragment
		Fragment fragToShow = null;
		if (cachedFragments[index] != null) { // 取缓存
			fragToShow = cachedFragments[index];
		} else {
			if(index == mainMenus.size()){
				List<StubObject> menuListTemp = new ArrayList<StubObject>();
				for(int i=TabBarNew.BOTTOM_ITEM;i<mainMenus.size();i++){
					menuListTemp.add(mainMenus.get(i));
				}
				fragToShow = new MoreMenuFrag(menuListTemp, this, TabBarNew.BOTTOM_ITEM);
				cachedFragments[index] = fragToShow; // 缓存
			}else
				fragToShow = initAndCacheFragment(index);
		}
		FragmentTransaction ft = obtainFragmentTransaction(index);
        getCurrentFragment().onPause(); // 暂停当前tab
        if(fragToShow.isAdded()){
       	 fragToShow.onStart(); // 启动目标tab的onStart()
        }else{
          ft.add(R.id.content, fragToShow);
        }
        showTab(index); // 显示目标tab
        ft.commit();
	}
	
	/**
	 * 创建并且缓存Fragment
	 * 
	 * @param index
	 */
	private Fragment initAndCacheFragment(int index) {
		Fragment frag = null;
		StubObject mainMenuItem = (StubObject) mainMenus.get(index);
		
		//frag = com.efounder.util.AbFragmentManager.getFragment(mainMenuItem);
		AbFragmentManager ab = new AbFragmentManager(this);
		
		frag = ab.getFragment(mainMenuItem);
		cachedFragments[index] = frag; // 缓存
		return frag;
	}
	/**
	 * 获取一个带动画的FragmentTransaction
	 * 
	 * @param index
	 * @return
	 */
	private FragmentTransaction obtainFragmentTransaction(int index) {
		FragmentTransaction ft = getSupportFragmentManager()
				.beginTransaction();
		// 设置切换动画
		if (index > currentTab) {
			ft.setCustomAnimations(R.anim.slide_left_in, R.anim.slide_left_out);
		} else {
			ft.setCustomAnimations(R.anim.slide_right_in,
					R.anim.slide_right_out);
		}
		return ft;
	}
	public Fragment getCurrentFragment() {
		return cachedFragments[currentTab];
	}
	/**
	 * 切换TAB
	 * @param idx
	 */
	private void showTab(int idx) {
		for (int i = 0; i < cachedFragments.length; i++) {
			Fragment fragment = cachedFragments[i];
			FragmentTransaction ft = obtainFragmentTransaction(idx);
			
			if(fragment!=null){
			if (idx == i) {
				ft.show(fragment);
			} else {
				ft.hide(fragment);
			}
			ft.commit();
			}
		}
		currentTab = idx; // 更新目标tab为当前tab
	}
	/**
	 * 显示fragment
	 */
	private void showFragment(Fragment frag) {
		FragmentTransaction tra = fm.beginTransaction();
		tra.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
		tra.replace(R.id.content, frag);
		tra.commit();
	}
	@Override
	protected void onPause() {
		titleName = (String) mTitleBar.getTitleTextButton().getText();
		super.onPause();
	}
	@Override
	protected void onResume() {
		mTitleBar.setTitleText(titleName);
		super.onResume();
	}
	//----------------提供接口--------------------
	public static MainFrameActivity getInstance(){
		return mySelf;
	}
/*	public void showForms(StubObject data) {
		AbLogUtil.i(TAG, "Fragment-->showForms");
		Intent intent = new Intent(this, FormsActivity.class);
		intent.putExtra("data", data);
		startActivity(intent);
	}*/
	public void jumpAndStoreStack(Fragment frag) {
		FragmentTransaction trasaction = fm.beginTransaction();
		trasaction.replace(R.id.content, frag);
		trasaction.addToBackStack(null);
		trasaction.commit();
	}
	public void popBackStack() {
		AbLogUtil.i(TAG, "Fragment-->popBackStack");
		fm.popBackStack();
	}
}
